package com.hxkj.shiro;

import com.hxkj.domain.po.AuthUser;
import com.hxkj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by admin on 2017/9/14.
 */
@Slf4j
public class ServiceLogoutFilter extends LogoutFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Value("${auth.sysKey}")
    private String sysKey;

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        String redirectUrl = getRedirectUrl(request, response, subject);
        try {
            subject.logout();
            // 业务上处理登出后的逻辑，如删除cookie等
            doLogout((HttpServletRequest) request, (HttpServletResponse) response);
        } catch (SessionException ise) {
            log.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
        }
        issueRedirect(request, response, redirectUrl);
        return false;
    }

    protected void doLogout(HttpServletRequest request, HttpServletResponse response)  throws Exception{
        // TODO: 2017/9/14 清除redis
        // 判断是否有该用户
        String account = request.getParameter("account");
        AuthUser user = userService.findByAccount(account);
        String key = user.getCredentialsSalt() + sysKey;
        redisTemplate.delete(key);

    }

}
